package hustlas.ball.driver;

import hustlas.ball.preparse.StringTokenTuple;
import hustlas.ball.preparse.Tokens;

import java.util.HashMap;
import java.util.Stack;

/**
 * This class serves as the parser driver and essentially takes the tokens
 * from the Lexer and a parsing table from the TableGen
 * 
 * @author Steven
 *
 */
public class ParserDriver {
	/*TODO: Handle checking if the inputted tokens will work with the supplied
	 * parse table and return the results
	 */
    public Stack<Tokens> tokens;
    public Stack<String> parseStack;
    public String[] nonTerminals;
    public String start;
    public ParserDriver(Stack<Tokens> tokens, String[] nonTerminals, String start){
        this.tokens = tokens;
        this.nonTerminals = nonTerminals;

        this.start = start;
    }
    
    public void parse(HashMap<StringTokenTuple,String[]> parseTable){
        String[] production;
    	Stack<String> parseStack = new Stack<String>();
        parseStack.add(start);
        while(!tokens.isEmpty()){
            if(tokens.peek() == Tokens.getToken(parseStack.peek())){ 
                //Match!
                parseStack.pop();
                tokens.pop();
            } else if (parseTable.get(new StringTokenTuple(parseStack.peek(), tokens.peek())) != null){//M[parseTable.peek(), inputTable.peek()] contains production A -> X1X2...Xn
            	production = parseTable.get(new StringTokenTuple(parseStack.peek(), tokens.peek()));
            	parseStack.pop();
                //for i := n downto 1 do
                
                //push Xi onto the parsing stack
            	for(int i = production.length - 1; i < -1; i--) {
                	parseStack.push(production[i]);
                }

                
            } else {
                System.err.println("you got an error");
                break;
            }
        }
        if(parseStack.isEmpty() && tokens.isEmpty()){
            System.out.println("The language is acceptable");
        } else {
            System.err.println("you got an error");
        }
    }
}
